<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    :before-close="handleClose"
    modal
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="100px">
      <ElFormItem label="上级机构" prop="parentId">
        <ElTreeSelect
          v-model="form.parentId"
          :data="deptOptions"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          placeholder="请选择上级机构"
          clearable
          style="width: 100%"
          check-strictly
        />
      </ElFormItem>

      <ElFormItem label="机构名称" prop="name">
        <ElInput v-model="form.name" placeholder="请输入机构名称" />
      </ElFormItem>

      <ElFormItem label="机构简称" prop="nameAbbr">
        <ElInput v-model="form.nameAbbr" placeholder="请输入机构简称" />
      </ElFormItem>

      <ElFormItem label="机构编码" prop="code">
        <ElInput v-model="form.code" placeholder="请输入机构编码" />
      </ElFormItem>

      <ElFormItem label="机构类型" prop="type">
        <ElSelect v-model="form.type" placeholder="请选择机构类型">
          <ElOption label="公司" value="1" />
          <ElOption label="部门" value="2" />
          <ElOption label="班组" value="3" />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="排序" prop="sort">
        <ElInputNumber v-model="form.sort" :min="1" :max="999" :step="1" />
      </ElFormItem>

      <ElFormItem label="备注">
        <ElInput v-model="form.remark" type="textarea" placeholder="请输入备注信息" :rows="3" />
      </ElFormItem>

      <ElFormItem label="状态">
        <ElSwitch v-model="form.status" :active-value="1" :inactive-value="0" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" @click="handleSubmit">确定</ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { getDeptTree } from '@/api/system-manage'
  import type { FormInstance, FormRules } from 'element-plus'
  import { computed, reactive, ref, watch } from 'vue'

  // 定义接口
  interface DeptFormData {
    id?: string
    parentId?: string
    name: string
    nameAbbr: string
    code: string
    type: string
    sort: number
    remark: string
    status: number
  }

  interface Props {
    visible: boolean
    editData: any
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit', data: DeptFormData): void
  }

  // Props
  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 响应式数据
  const dialogVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
  })

  const formRef = ref<FormInstance>()
  const deptOptions = ref<any[]>([]) // 上级机构选项
  const form = reactive<DeptFormData>({
    name: '',
    nameAbbr: '',
    code: '',
    type: '2',
    sort: 1,
    remark: '',
    status: 1
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入机构名称', trigger: 'blur' },
      { min: 1, max: 20, message: '机构名称长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    nameAbbr: [
      { required: true, message: '请输入机构简称', trigger: 'blur' },
      { min: 1, max: 10, message: '机构简称长度在 1 到 10 个字符', trigger: 'blur' }
    ],
    code: [
      { required: true, message: '请输入机构编码', trigger: 'blur' },
      { min: 1, max: 20, message: '机构编码长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    type: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
  })

  // 计算属性
  const dialogTitle = computed(() => {
    return props.editData?.id ? '编辑机构' : '新增机构'
  })

  // 获取上级机构选项
  const loadDeptOptions = async () => {
    try {
      const response = await getDeptTree()
      deptOptions.value = response || []
    } catch (error) {
      console.error('获取机构列表失败:', error)
      deptOptions.value = []
    }
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(form, {
      name: '',
      nameAbbr: '',
      code: '',
      type: '2',
      sort: 1,
      remark: '',
      status: 1,
      parentId: undefined,
      id: undefined
    })
  }

  // 填充表单数据
  const fillFormData = () => {
    if (props.editData) {
      Object.assign(form, props.editData)
    }
  }

  // 监听编辑数据变化
  watch(
    () => props.editData,
    (newVal) => {
      if (newVal) {
        fillFormData()
      }
    },
    { immediate: true }
  )

  // 监听弹窗显示状态
  watch(
    () => props.visible,
    async (visible) => {
      if (visible) {
        // 加载上级机构选项
        await loadDeptOptions()
        // 确保机构数据加载完成后再填充表单数据
        if (props.editData) {
          fillFormData()
        } else {
          resetForm()
        }
      } else {
        // 弹窗关闭时重置表单
        resetForm()
      }
    }
  )

  // 处理关闭
  const handleClose = () => {
    resetForm()
    dialogVisible.value = false
  }

  // 处理提交
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate((valid) => {
      if (valid) {
        // 不再使用try-catch捕获emit的结果，因为Vue的emit通常不直接支持Promise返回值传递
        // 成功提示和对话框关闭由父组件在API调用成功后处理
        // 错误处理也由父组件完成并显示错误消息
        emit('submit', { ...form })
        // 这里不显示成功消息和关闭对话框，留给父组件处理
      }
    })
  }
</script>

<style lang="scss" scoped>
  .el-dialog__header {
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
  }

  .el-dialog__title {
    font-size: 16px;
    font-weight: 500;
  }

  .el-dialog__body {
    padding: 25px 20px;
  }

  .el-form-item__label {
    font-weight: 400;
  }

  .el-input-number {
    width: 100%;
  }
</style>
